//在线用户
const jsonfile = require('jsonfile');
const moment = require('moment');
const {difference} =require('loadsh')
//当前在线人数
function saveMsg(data){
    let {to,msg,from}=data
    const today = moment().format('YYYY-MM-DD');
    const create_time = moment().format('YYYY-MM-DD HH:mm:ss');
    let socketList={}
    try {
        socketList=jsonfile.readFileSync(`data/socket/${today}.json`)
    }catch {}
    if(!socketList[to]){
        socketList[to]=[{create_time,msg,from,to}]
    }else {
        socketList[to].push({create_time,msg,from,to})
    }
    //群聊消息
    if(global.socketList){
        if(to==='groupChat'){
            const notOnlineUser=difference(global.userList,global.socketList);
            notOnlineUser.map(username=>{
                if(!global.socketInfo[`groupChat_${username}`]){
                    global.socketInfo[`groupChat_${username}`]={from,to:'groupChat',unreadCount:1,msg}
                }else {
                    global.socketInfo[`groupChat_${username}`].msg=msg
                    global.socketInfo[`groupChat_${username}`].unreadCount++
                }
            })
        }else {
            const index=global.socketList.findIndex(username=>username===to)
            if(index<0 && global.socketInfo){
                if(!global.socketInfo[to]){
                    global.socketInfo[to]={from,unreadCount:1,msg}
                }else {
                    global.socketInfo[to].msg=msg
                    global.socketInfo[to].unreadCount++
                }
            }
        }
    }
    jsonfile.writeFileSync(`data/socket/${today}.json`,socketList)
}
const initIoFun=function (io){
    // 當發生連線事件
    io.use((socket, next) => {
        if (global.authorizationList.includes(socket.request.headers.authorization)) return next();
        next(new Error('Authentication error'));
    });
    io.on('connection', (socket) => {
        console.log(`初始化socket`)
        /*const { roomName} = socket.handshake.query
        console.log(roomName)
        const roomChatFile=`${roomName}_${create_time}`
        if(roomName){
            socket.join(roomName)
            let socketList={}
            try {
                socketList=jsonfile.readFileSync(`data/socket/${roomChatFile}.json`)
            }catch {}
            jsonfile.writeFileSync(`data/socket/${roomChatFile}.json`,socketList)
            if(!global.socketInfo){
                global.socketInfo={}
            }
            const notOnlineUser=difference(global.userList,global.socketList)
            socket.on('message', data => {
                const msgItem = {
                    from:data.from,
                    room: roomName,
                    create_time: create_time,
                    msg: data.msg
                }
                notOnlineUser.map(username=>{
                    if(!global.socketInfo[roomName]){
                        global.socketInfo[roomName]=[{...msgItem,unreadCount:1,to:username}]
                    }else {
                        const index=global.socketInfo[roomName].findIndex(i=>i.to===username)
                        if(index>-1){
                            Object.assign(global.socketInfo[roomName][index],msgItem)
                            global.socketInfo[roomName][index].unreadCount++
                        }else {
                            global.socketInfo[roomName].push({...msgItem,unreadCount:1,to:username})
                        }
                    }
                })
                socket.to(roomName).emit('groupChat', msgItem)
            })
        }else {
            socket.leave(roomName);
        }*/
        socket.on('login', authorization=>{
            const username=authorization.split('-')[0]
            socket.name = username
            console.log(`${socket.name}连接`)
            if(!global.socketInfo){
                global.socketInfo= {}
            }
            if(!global.socketList){
                global.socketList=[username]
            }else {
                if(!global.socketList.includes(username)){
                    global.socketList.push(username)
                }
            }
            io.emit('login', username);
        })
        socket.on('groupChat', ({from,to,msg},fun)=> {
            fun('done');
            saveMsg({msg,to:'groupChat',from})
            io.emit('groupChat',{msg,from,to:'groupChat'});
        })
        socket.on('send', ({from,to,msg},fun)=> {
            fun('done');
            //存储消息
            saveMsg({from,to,msg})
            //回复消息
            from!==to && io.emit(to,{msg,from,to});
        });
        socket.on('disconnect', () => {
            //将退出的用户从在线列表中删除
            if(global.socketList){
                const index=global.socketList.findIndex(username=>username===socket.name)
                index>-1 && global.socketList.splice(index,1)
            }
            io.emit('logout',socket.name);
            console.log(`${socket.name}断开连接`)
        });
    });
}
module.exports=initIoFun
